import http from "../utils/http";

export const loginService = (params) => {
  return http.post(`/user/login`, { jsCode: params });
};

export const registService = (params) => {
  return http.post(`/user/region`, params);
};

export const getUserInfoService = () => {
  return http.get("/user/getuserinfo");
};

/**
 * @description 实现本地资源上传
 * @param {*} filePath 要上传的文件路径
 * @param {*} name 文件对应的key
 * @returns Promise
 */
export const uploadAvatarService = (filePath, name) => {
  return http.upload("/user/uploadavatar", filePath, name);
};

export const uploadCoverService = (filePath, name) => {
  return http.upload("/user/uploadbg", filePath, name);
};
/**
 * @description 更新用户账号的信息(旧版)
 */
export const updateUserInfoService = (param) => {
  return http.post("/user/update", param);
};

/**
 * @description 构造用户更新请求的数据体（辅助函数）
 * @param {Object} userInfo 当前完整的用户信息
 * @param {Object} updatedFields 需要更新的字段（只包含要改的项）
 * @returns {Object} 合并后的请求体 默认保留原值，仅更新传入的字段
 */
const buildUpdatePayload = (userInfo, updatedFields) => {
  return {
    phone: userInfo.phone || "",
    nickname: userInfo.nickname || "",
    email: userInfo.email || "",
    school: userInfo.school || null,
    grade: userInfo.grade || null,
    major: userInfo.major || null,
    coverImage: userInfo.coverImage || "",
    avatarUrl: userInfo.avatarUrl || "",
    gender: userInfo.gender || null,
    age: userInfo.age || "",
    personality: userInfo.personality || "",
    mbti: userInfo.mbti || "",
    persona: userInfo.persona || "",
    projectOrientation: userInfo.projectOrientation || "",
    introduction: userInfo.introduction || "",
    ...updatedFields, // ✅ 覆盖对应字段
  };
};

/**
 * @description 更新用户账号的信息(新版)
 * @param {Object} userInfo 当前完整的用户信息（通常来自 userStore.userInfo）
 * @param {Object} updatedFields 需要更新的字段对象（例如 { nickname: "小红" }）
 * @returns {Promise} 返回 Promise，resolve 为接口响应数据
 * 
 * @example
 * try {
 *   const res = await updateUserInfo(this.data.userInfo, { nickname: "小红", gender: 1 });
 *   console.log("修改成功", res);
 * } catch (err) {
 *   console.error("修改失败", err);
 * }
 */
export const updateUserInfo = (userInfo, updatedFields) => {
  const payload = buildUpdatePayload(userInfo, updatedFields);
  return http.post("/user/update", payload);
};

export const getPhoneService = (code) => {
  return http.post("/user/getphone", { code: code });
};

/**
 * @description 刷新用户token
 * @param {number} id 用户ID
 * @param {string} openid 用户openid
 * @returns Promise
 */
export const updateUserTokenService = (id, openid) => {
  return http.post("/user/updateusertoken", { id, openid });
};